package com.sir.tao.carhire.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.sir.tao.carhire.entity.table.AdministratorsEntity;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.Objects;

@Component
public class MetaHandler implements MetaObjectHandler {

    /**
     * 插入时的填充策略
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        boolean hasSetter = metaObject.hasSetter("createTime");
        Subject subject = SecurityUtils.getSubject();
        AdministratorsEntity administratorsEntity = (AdministratorsEntity) subject.getPrincipal();
        //获取用户名和权限

        if (hasSetter) {
            this.setFieldValByName("createTime", new Date(), metaObject);
            if (Objects.nonNull(administratorsEntity)){
                this.setFieldValByName("createBy", administratorsEntity.getUsername(), metaObject);
            }
            this.setFieldValByName("updateTime", new Date(), metaObject);
        }
    }

    /**
     * 更新时的填充策略
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Subject subject = SecurityUtils.getSubject();
        AdministratorsEntity administratorsEntity = (AdministratorsEntity) subject.getPrincipal();
        this.setFieldValByName("updateTime", new Date(), metaObject);
        if (Objects.nonNull(administratorsEntity)){
            this.setFieldValByName("createBy", administratorsEntity.getUsername(), metaObject);
        }
    }
}
